﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace Smith.ImageConverter
{
    public partial class AppForm : Form
    {
        public AppForm()
        {
            InitializeComponent();
            this.Icon = Properties.Resources.Icon;
        }

        private void FormLoad(object sender, EventArgs e)
        {
            LoadSettings();            
        }

        private void OnFormClosing(object sender, FormClosingEventArgs e)
        {
            SaveSettings();
            Properties.Settings.Default.Save();
            TaskList.Items.Clear();
        }

        private void OutputDirectoryText_TextChanged(object sender, EventArgs e)
        {
            UpdateDirectoryValidation();            
        }

        private void SelectOutputDirectory(object sender, EventArgs e)
        {
            if (!CheckOutputInSource.Checked)
            {
                FolderBrowserDialog fb = new FolderBrowserDialog();
                fb.ShowNewFolderButton = true;
                fb.Description = Properties.Resources.SelectOutDescription;
                DialogResult r = fb.ShowDialog();
                if (r == DialogResult.OK)
                {
                    Properties.Settings.Default.OutputDirectory =
                    OutputDirectoryText.Text = fb.SelectedPath;
                }
                fb.Dispose();
            }
        }

        private void CheckOutputInSource_CheckedChanged(object sender, EventArgs e)
        {
            OutputDirectoryText.ReadOnly = CheckOutputInSource.Checked;
            Properties.Settings.Default.OutputOption =
                (int)(CheckOutputInSource.Checked ? OutputOption.InOriginal : OutputOption.InDirectory);
        }

        private void CheckDeleteSource_CheckChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.DeleteSource = CheckDeleteSource.Checked;
        }

        private void CheckSizeChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.CheckSize = CheckCheckSize.Checked;
        }

        private void SearchSubChanged(object sender, EventArgs e)
        {
            Properties.Settings.Default.SearchSub = CheckSearchSub.Checked;
        }

        private void OnMouseHover(object sender, EventArgs e)
        {
            Label l = sender as Label;
            l.Image = Properties.Resources.ButtonHover;
        }

        private void OnMouseLeave(object sender, EventArgs e)
        {
            Label l = sender as Label;
            l.Image = Properties.Resources.ButtonNormal;
        }

        private void OnMouseDown(object sender, MouseEventArgs e)
        {
            Label l = sender as Label;
            l.Image = Properties.Resources.ButtonDown;
        }

        private void OnMouseUp(object sender, MouseEventArgs e)
        {
            Label l = sender as Label;
            l.Image = Properties.Resources.ButtonHover;
        }

        /// <summary>
        /// fire when advance setting button is clicked, to show advance setting dialog
        /// </summary>
        private void OpenAdvanceSetting(object sender, EventArgs e)
        {
            SaveSettings();
            using (AdvanceForm af = new AdvanceForm())
            {
                DialogResult r = af.ShowDialog();
                if (r == DialogResult.OK) LoadSettings();
            }
        }

        /// <summary>
        /// fire when add files button is clicked, to add files to task list
        /// </summary>
        private void ButtonAddFilesClick(object sender, EventArgs e)
        {
            using (OpenFileDialog d = new OpenFileDialog())
            {
                d.Title = "Add Files";
                d.Multiselect = true;
                d.RestoreDirectory = true;
                d.Filter = Properties.Resources.FileFilterText;
                DialogResult r = d.ShowDialog();
                if (r == DialogResult.OK)
                {
                    AddFiles(d.FileNames, Properties.Settings.Default.CheckSize);
                    UpdateFileCount();
                }
            }
        }

        /// <summary>
        /// fire when add from directory button is clicked, to add files from directory to task list
        /// </summary>
        private void ButtonAddFromDirectoryClick(object sender, EventArgs e)
        {
            using (FolderBrowserDialog d = new FolderBrowserDialog())
            {
                d.ShowNewFolderButton = false;
                d.Description = Properties.Resources.SelectInDescription;
                DialogResult r = d.ShowDialog();
                if (r == DialogResult.OK)
                {
                    AddFromDirectory(d.SelectedPath, Properties.Settings.Default.CheckSize);
                    UpdateFileCount();
                }
            }
        }

        /// <summary>
        /// fire when delete selected button is clicked, to delete the seleted item in task list
        /// </summary>
        private void ButtonDeleteSelectedClick(object sender, EventArgs e)
        {
            var indeces = TaskList.SelectedIndices;
            for (int i = indeces.Count - 1; i >= 0; i--)
            {
                TaskList.Items.RemoveAt(indeces[i]);
            }
            UpdateFileCount();
        }

        /// <summary>
        /// fire when clear button is clicked, to delete all items in task list
        /// </summary>
        private void ButtonClearAllClick(object sender, EventArgs e)
        {
            TaskList.Items.Clear();
            UpdateFileCount();
        }

        /// <summary>
        /// fire when item in task list is clicked, to open the file with default program
        /// </summary>
        private void TaskListDoubleClick(Object sender, EventArgs e)
        {
            ListViewItem selectItem = TaskList.SelectedItems[0];
            if (selectItem != null)
            {
                string file = selectItem.SubItems[0].Text;
                try
                {
                    System.Diagnostics.Process.Start(file);
                }
                catch (Exception) { }
            }
        }
       
        private void LoadSettings()
        {
            OutputDirectoryText.Text = Properties.Settings.Default.OutputDirectory;
            CheckSearchSub.Checked = Properties.Settings.Default.SearchSub;
            CheckCheckSize.Checked = Properties.Settings.Default.CheckSize;
            CheckOutputInSource.Checked = (Properties.Settings.Default.OutputOption == (int)OutputOption.InOriginal);
            CheckDeleteSource.Checked = Properties.Settings.Default.DeleteSource;
            
            switch ((ConvertType)Properties.Settings.Default.ConvertType)
            {
                case ConvertType.PNG:
                    RBTargetPng.Checked = true;
                    break;
                case ConvertType.BMP:
                    RBTargetBmp.Checked = true;
                    break;
                default:
                    RBTargetJpeg.Checked = true;
                    break;
            }
        }

        private void SaveSettings()
        {
            Properties.Settings.Default.OutputDirectory = OutputDirectoryText.Text;
            Properties.Settings.Default.SearchSub = CheckSearchSub.Checked;
            Properties.Settings.Default.CheckSize = CheckCheckSize.Checked;
            Properties.Settings.Default.OutputOption = (int)(CheckOutputInSource.Checked ? OutputOption.InOriginal : OutputOption.InDirectory);
            Properties.Settings.Default.DeleteSource = CheckDeleteSource.Checked;

            if (RBTargetPng.Checked)
            {
                Properties.Settings.Default.ConvertType = (int)ConvertType.PNG;
            }
            else if (RBTargetBmp.Checked)
            {
                Properties.Settings.Default.ConvertType = (int)ConvertType.BMP;
            }
            else
            {
                Properties.Settings.Default.ConvertType = (int)ConvertType.JPEG;
            }
            
        }

        /// <summary>
        /// add file to task list
        /// </summary>
        private void AddFiles(string[] files, bool checkSize)
        {
            if (checkSize)
            {
                foreach (string file in files)
                {
                    if (System.IO.File.Exists(file))
                    {
                        try
                        {
                            ListViewItem item = new ListViewItem(file);
                            Bitmap img = new Bitmap(file);
                            string size = string.Format("{0}x{1}", img.Width, img.Height);
                            item.SubItems.Add(size);                            
                            TaskList.Items.Add(item);
                            img.Dispose();
                        }
                        catch (Exception)
                        {
                            continue;
                        }
                    }
                }
            }
            else
            {
                foreach (string file in files)
                {
                    TaskList.Items.Add(file);
                }
            }
        }

        /// <summary>
        /// add files to task list from directory
        /// </summary>
        private void AddFromDirectory(string path, bool checkSize)
        {
            SearchOption option = SearchOption.TopDirectoryOnly;
            if (Properties.Settings.Default.SearchSub) option = SearchOption.AllDirectories;
            string[] paterns = Properties.Resources.FileFilter.Split(new char[] { '|' });
            foreach (var item in paterns)
            {
                string[] files = System.IO.Directory.GetFiles(path, item, option);
                AddFiles(files, checkSize);
            }            
        }

        /// <summary>
        /// fire when start convert button is clicked, to start to process the converting task
        /// </summary>
        private void StartConvert(object sender, EventArgs e)
        {
            SaveSettings();
            if (TaskList.Items.Count == 0) return;            
            if (CheckOutputInSource.Checked == false)
            {
                try
                {
                    OutputDirectoryText.Text = Path.GetFullPath(OutputDirectoryText.Text);
                    if (Directory.Exists(OutputDirectoryText.Text) == false)
                    {
                        Directory.CreateDirectory(OutputDirectoryText.Text);
                        Properties.Settings.Default.OutputDirectory = OutputDirectoryText.Text;
                        UpdateDirectoryValidation();
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Message", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
            }
            using (ConvertForm cf = new ConvertForm(TaskList.Items))
            {
                cf.ShowDialog();
            }
        }

        /// <summary>
        /// open about dialog
        /// </summary>
        private void OpenAboutDialog(object sender, EventArgs e)
        {
            using (About a = new About())
            {
                a.ShowDialog();
            }
        }

        private void UpdateFileCount()
        {
            LBFileCount.Text = "Task List";
            if (TaskList.Items.Count > 0)
                LBFileCount.Text += string.Format(" ({0})", TaskList.Items.Count);
        }

        private void UpdateDirectoryValidation()
        {
            if (Directory.Exists(OutputDirectoryText.Text))
                ImageAvailable.BackgroundImage = Properties.Resources.Available;
            else ImageAvailable.BackgroundImage = null;
        }
    }
}
